package com.lipaluma.field.mapper.mapping;

import java.lang.reflect.Field;

import com.lipaluma.io.Row;


public class Column implements FieldMappingInfo {
	private Integer columnIndex;
	private String columnName;
	
	public Column(String name, int index) {
		columnName = name;
		columnIndex = index-1;
	}
	public Column(int index) {
		columnIndex = index-1;
	}
	public Column(String name) {
		columnName = name;
	}
	private Column(Builder builder) {
		this.columnIndex = builder.columnIndex;
		this.columnName = builder.columnName;
	}
	
	@Override
	public void onField(Field field) {
		if(columnName == null)
			this.columnName = field.getName();
	}

	@Override
	public void withFieldAndPosition(Field field, int position) {
		if(columnName == null)
			this.columnName = field.getName()+"_"+position;
	}
	
	public Integer getColumnIndex() {
		return columnIndex;
	}
	
	public String getColumnName() {
		return columnName;
	}
	
	public boolean mapHeader(String name, int index) {
		if(name.equalsIgnoreCase(columnName)) {
			if(columnIndex == null)
				this.columnIndex = index;
			return true;
		}
		return false;
	}

	public void setColumnName(String column) {
		this.columnName = column;
	}
	
	public void writeHeader(Row row) {
		row.writeValue(columnName, this);
	}
	
//	public void writeHeader(ObjectMarshalled objectMarshalled) {
//		objectMarshalled.addValueMarshalledOnMapping(field, mapping, value);
//	}
	
	@Override
	public String toString() {
		if(columnIndex == null)
			return "column [index='not mapped yet', name="+columnName+"]";
		return "column [index="+(columnIndex+1)+", name="+columnName+"]";
	}
	
	public static Builder builder() {
		return new Builder();
	}

	public static class Builder {
		private Integer columnIndex;
		private String columnName;
		
		public Builder withColumnIndex(int columnIndex) {
			this.columnIndex = columnIndex;
			return this;
		}
		
		public Builder withColumnName(String columnName) {
			this.columnName = columnName;
			return this;
		}
		
		public Column build() {
			return new Column(this);
		}
	}
}
